import random
import json
import requests
from typing import List, Dict

# 专家属性定义
PERSONAL_TRAITS = [
    "严谨的", "犀利的", "温和的", "挑剔的", "宽容的",
    "专业的", "仔细的", "严格的", "友好的", "批判性的"
]

LANGUAGE_STYLES = [
    "专业术语丰富", "通俗易懂", "委婉含蓄", "直接了当", "引经据典",
    "数据驱动", "案例丰富", "逻辑严密", "简明扼要", "详细深入"
]

EXPERT_FIELDS = [
    "人工智能", "生物医学", "经济学", "物理学", "心理学",
    "计算机科学", "环境科学", "社会学", "教育学", "工程学"
]

def generate_experts(num: int = 5) -> List[Dict]:
    """生成指定数量的专家角色"""
    experts = []
    for i in range(num):
        expert = {
            "id": i + 1,
            "name": f"专家{i+1}",
            "trait": random.choice(PERSONAL_TRAITS),
            "style": random.choice(LANGUAGE_STYLES),
            "field": random.choice(EXPERT_FIELDS)
        }
        experts.append(expert)
    return experts


def expert_speak(api_key: str, expert: Dict, topic: str, discussion_history: List[str]) -> str:
    """让专家发言"""
    url = "https://api.deepseek.com/chat/completions"
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': f'Bearer {api_key}'
    }
    
    # 优化历史记录截取（保留最近10条发言）
    history_str = "\n---\n".join(discussion_history[-10:]) if discussion_history else "暂无讨论历史"
    
    system_prompt = (
        f"你是一位{expert['field']}领域的{expert['trait']}专家，"
        f"擅长{expert['style']}的表达方式。\n"
        f"当前讨论主题：{topic}\n\n"
        "请按以下要求发言：\n"
        "1. 先简要回应1-2个之前的观点（赞同/补充/质疑）\n"
        "2. 从专业角度提出新的见解\n"
        "3. 语言自然口语化，避免使用第一人称\n"
        f"最近的讨论记录：\n{history_str}"
    )
    
    payload = json.dumps({
        "messages": [
            {"content": system_prompt, "role": "system"},
            {"content": "请基于讨论历史发表观点，注意与其他专家互动", "role": "user"}
        ],
        "model": "deepseek-chat",
        "temperature": 0.8,  # 适当提高温度值增加多样性
        "max_tokens": 350,
        "top_p": 0.9
    })
    
    try:
        response = requests.post(url, headers=headers, data=payload)
        response.raise_for_status()
        result = response.json()
        content = result['choices'][0]['message']['content']
        
        # 清理可能出现的编号格式
        return content.split('\n')[-1].strip()  # 取最后一段作为核心观点
    except Exception as e:
        print(f"专家发言失败: {str(e)}")
        return f"{expert['name']}发言时出现错误"


# 在专家属性定义后添加
INTERJECTOR_TRAITS = [
    "神秘的", "古怪的", "直觉型的", "天马行空的", "直言不讳的",
    "幽默的", "挑衅的", "哲学性的", "反传统的", "超然的"
]

# 替换原有的INTERJECTOR_FIELDS定义
INTERJECTOR_FIELDS = [
    "科技哲学", "认知科学", "科学史", "技术伦理学", 
    "科学社会学", "知识论", "科学传播学", "创新研究",
    "系统科学", "复杂系统研究", "科技政策", "跨学科方法论"
]

def generate_interjector() -> Dict:
    """生成随机插嘴人物"""
    return {
        "name": "神秘人",
        "trait": random.choice(INTERJECTOR_TRAITS),
        "field": random.choice(INTERJECTOR_FIELDS)
    }

def interject(api_key: str, recent_comments: List[str]) -> str:
    """随机人物插嘴发言"""
    url = "https://api.deepseek.com/chat/completions"
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': f'Bearer {api_key}'
    }
    
    interjector = generate_interjector()
    context = "\n".join(recent_comments[-2:]) if len(recent_comments) >= 2 else recent_comments[0] if recent_comments else "无上下文"
    
    system_prompt = (
        f"你是一个{interjector['trait']}的{interjector['field']}研究者，"
        "突然插入了这场讨论。\n"
        "发言要求：\n"
        "1. 仅回应最近两条发言内容\n"
        "2. 提出独特或另类观点\n"
        "3. 发言风格要符合你的特质\n"
        "4. 总字数不超过400字\n"
        f"最近的发言：\n{context}"
    )
    
    payload = json.dumps({
        "messages": [
            {"content": system_prompt, "role": "system"},
            {"content": "请发表你的看法", "role": "user"}
        ],
        "model": "deepseek-chat",
        "temperature": 1.0,  # 使用更高温度值增加随机性
        "max_tokens": 500,
        "top_p": 0.95
    })
    
    try:
        response = requests.post(url, headers=headers, data=payload)
        response.raise_for_status()
        result = response.json()
        content = result['choices'][0]['message']['content']
        return f"{interjector['name']}({interjector['field']})｜随机插嘴：\n{content}"
    except Exception as e:
        print(f"插嘴发言失败: {str(e)}")
        return f"神秘人插嘴时出现错误"

# 在generate_experts函数后添加
def host_opening_statement(api_key: str, topic: str) -> str:
    """主持人开场陈述"""
    url = "https://api.deepseek.com/chat/completions"
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': f'Bearer {api_key}'
    }
    
    system_prompt = (
        "你是一位学术讨论会的主持人，需要做一个简短的开场陈述。\n"
        "要求：\n"
        "1. 简要介绍讨论主题的背景\n"
        "2. 提出2-3个关键问题引导讨论\n"
        "3. 语言简洁明了，不超过200字\n"
        f"讨论主题：{topic}"
    )
    
    payload = json.dumps({
        "messages": [
            {"content": system_prompt, "role": "system"},
            {"content": "请做开场陈述", "role": "user"}
        ],
        "model": "deepseek-chat",
        "temperature": 0.7,
        "max_tokens": 300
    })
    
    try:
        response = requests.post(url, headers=headers, data=payload)
        response.raise_for_status()
        result = response.json()
        return result['choices'][0]['message']['content']
    except Exception as e:
        print(f"开场陈述生成失败: {str(e)}")
        return "主持人开场陈述生成失败"

# 修改main函数
def main():
    api_key = "xxxx"  # 替换为你的DeepSeek API key
    topic = input("请输入讨论主题: ")
    
    experts = generate_experts()
    print("\n专家组成员:")
    for expert in experts:
        print(f"{expert['name']}: {expert['trait']}的{expert['field']}专家，擅长{expert['style']}的表达")
    
    discussion_history = []
    round_summaries = []
    
    # 添加主持人开场
    print("\n=== 主持人开场 ===")
    opening = host_opening_statement(api_key, topic)
    print(opening)
    
    # 记录开场陈述
    discussion_history.append(f"主持人｜开场陈述：\n{opening}")
    with open("discussion_log.txt", "a", encoding="utf-8") as f:
        f.write(f"主持人｜开场陈述：\n{opening}\n\n")
    
    # 后续讨论保持不变
    for round_num in range(1, 10):
        print(f"\n=== 第{round_num}轮讨论 ===")
        
        for expert in experts:
            print(f"\n{expert['name']}正在发言...")
            speech = expert_speak(api_key, expert, topic, discussion_history)
            print(speech)
            
            record = f"{expert['name']}｜{expert['field']}｜第{len(discussion_history)//5 +1}次发言：\n{speech}"
            discussion_history.append(record)
            
            with open("discussion_log.txt", "a", encoding="utf-8") as f:
                f.write(f"{record}\n\n")
            
            # 添加随机插嘴逻辑
            if random.random() < 0.2:  # 20%几率插嘴
                print("\n>>> 有人突然插嘴！")
                interjection = interject(api_key, discussion_history[-2:])
                print(interjection)
                
                discussion_history.append(interjection)
                with open("discussion_log.txt", "a", encoding="utf-8") as f:
                    f.write(f"{interjection}\n\n")
        
        # 每3轮进行一次总结
        if round_num % 3 == 0:
            print("\n正在进行阶段性总结...")
            summary = summarize_discussion(api_key, topic, discussion_history[-15:])
            if summary["status"] == "success":
                summary_text = f"=== 第{round_num//3}次阶段性总结 ===\n{summary['summary']}\n"
                round_summaries.append(summary_text)
                print(summary_text)
                
                with open("discussion_summaries.txt", "a", encoding="utf-8") as f:
                    f.write(summary_text + "\n")
    
    # 最终总结
    print("\n正在进行最终总结...")
    final_summary = summarize_discussion(api_key, topic, discussion_history)
    if final_summary["status"] == "success":
        final_text = f"=== 最终总结 ===\n{final_summary['summary']}\n"
        print(final_text)
        
        with open("discussion_summaries.txt", "a", encoding="utf-8") as f:
            f.write(final_text + "\n")

if __name__ == "__main__":
    main()